layui.use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    form.on("submit(addUser)", function (data) {
        var jsondata = {
            userId: $("#userId").val(),
            username: $("#username").val(),
            email: $("#email").val(),
            mobile: $("#mobile").val(),
            status: data.field.status,
            roleIds: getRoles()
        };
        $.ajax({
            type: 'post',
            url: "/admin/sys/user/save.do",
            async : false,
            data: JSON.stringify(jsondata),
            success: function (res) {
                if (res.code == 0) {
                    top.layer.msg("操作成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                    form.render();
                } else {
                    layer.msg(res.msg);
                }
            },
            contentType: 'application/json;charset=utf-8',
            dataType: 'json'
        });
    });

    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    function loadRoles(){
        $.get("/admin/sys/role/getRoleWithUserRoleInfo.do", {userId: getQueryString("userId")}, function (res) {
            var list = res.data;
            $.each(list, function (i, role) {
                $('#roles').append('<input type="checkbox"  value="' + role.roleId + '" title="' + role.remark + '"'
                    + (role.hasOwn == 1 ? 'checked' : '') + '>');
            });
            form.render('checkbox');
        });
    };

    //渲染角色
    $(document).ready(function () {
        loadRoles();
    });

    function getRoles() {
        var roles = "";
        $("input[type='checkbox']:checked").each(function (i) {
            if (i == 0) {
                roles = $(this).val();
            } else {
                roles = roles + "," + $(this).val();
            }
        });
        return roles;
    };
});
